#include <slothttpd/config/server.hpp>
#include <slothttpd/config/create_location.hpp>
#include <slothttpd/connection.hpp>

#include <boost/filesystem.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/make_shared.hpp>

namespace slothttpd {
namespace config {

server::server(const boost::property_tree::ptree &node, configuration &c) :
    conf(c)
{
    for (auto &v : node.get_child("name")) {
        name.push_back(v.second.data());
    }
    
    path    = boost::filesystem::path(node.get<std::string>("path")).normalize().string();
    index   = boost::filesystem::path(node.get<std::string>("index")).normalize().string();
    
    for (auto &v : node.get_child("locations")) {
        auto dest = v.second.get<std::string>("dest");
        locations.push_back(create_location(dest, v.second, *this));
    }
}

bool server::match_host(char_range_t host) const
{
    for (auto &n : name) {
        if (host == n)
            return true;
    }
    
    return false;
}

std::ostream &operator<<(std::ostream &os, const server &s)
{
    os << "  --- server ---\n"
       << "      name : " << boost::algorithm::join(s.name, ", ") << '\n'
       << "      path : " << s.path << '\n'
       << "      index: " << s.index << '\n';

    for (auto &l : s.locations) {
        os << (*l);
    }
    
    return os;
}

}
}
